//
//  ZZCOAuthViewController.swift
//  weibo
//
//  Created by zhangzuchao on 17/3/27.
//  Copyright © 2017年 zhangZuChao. All rights reserved.
//https://api.weibo.com/oauth2/authorize?client_id=1480060059&redirect_uri=http://www.baidu.com


import UIKit
import SVProgressHUD
//微博的AppKey
let AppKey = "1480060059"
//授权回调页地址
let Redirect_Uri = "http://www.baidu.com"
//  微博的AppSecret
let AppSecret = "d64a8a75173b2f66b27bdb4fb28b7e1a"

class ZZCOAuthViewController: UIViewController {

    //懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    //重写加载view的方法
    override func loadView() {
        webView.delegate = self
        //加载自定义视图
        view = webView

    }
    
    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupNavUI()
        requestOAuth()
    }
    
    //用webview加载登录界面
    private func requestOAuth(){
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
      print(urlStr)
        let urlRequest = URLRequest(url: URL(string: urlStr)!)
        
        webView.loadRequest(urlRequest)
    }
    
    //  设置导航栏按钮和标题
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        navigationItem.title = "微博登录"
    }
    

    
    //导航栏按钮点击事件
   @objc private func cancelAction(){
    dismiss(animated: true, completion: nil)
    }
    
    //自动填充自己的账号和密码
   @objc private func autoFillAction(){
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '1297172977@qq.com';document.getElementById('passwd').value = '123456';")
        
    }
    
    
    
 }

//   实现代理方法
extension ZZCOAuthViewController: UIWebViewDelegate {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //  守护urlstr一定有值
        guard let urlStr = request.url?.absoluteString else {
            return false
        }
        
        //  如果回调网址不对直接return
        if !urlStr.hasPrefix(Redirect_Uri) {
            return true
        }
        
        //  代码执行到此表示是我们关心的回调地址, query表示请求的参数
        if let query = request.url?.query, query.hasPrefix("code=") {
            
            //  截取授权码(code)
            let code = query.substring(from: "code=".endIndex)
            
            //  通过viewmode实例调用获取accessToken
            ZZCUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                if isSuccess {
 
                    //  进入欢迎界面
                    //  先把当前OAuth控制dismis
                    self.dismiss(animated: false, completion: {
                        
                        //  需要等到dismis操作完成以后再去发送切换根视图控制器的通知,否则会有内存泄漏
                        //  发送切换根视图的通知
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                    
                } else {
                    print("登录失败")
                }
            })
            
        } else {
            
            //  点击是取消授权
            dismiss(animated: true, completion: nil)
        }
        
        print(urlStr)
        //  不加载授权回调地址和取消授权回调地址
        return false
        
    }
    
    //  已经开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        //  显示等待指示视图
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //  移除等待指示视图
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //  移除等待指示视图
        SVProgressHUD.dismiss()
    }
    
}


